package org.shnux.android.bingo;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.io.File; 

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;

import android.app.Activity;
import android.os.Bundle;
import android.view.View; 
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
 
public class TextEditor extends Activity {
    /** Called when the activity is first created. */
	public EditText et;
	public TextView txt1;
	String FILENAME = "hello_file10";
	public ListView lv1;
	public String lv_arr[]={"analogous","ball park","benchmark","best practice","blame culture","bottom line","challenge","implement","differential","diversity","empower","envision","fast track","hardball","leverage","metrics","paradigm","performance","pinch point","proactive","revisit","strategy","timeline","clarify    on","robust","focus","revisit","silo","pinch point","touch base","core business","mindset","networking","envision","strategic fit","core business","diversity","timeline","metrics","touch base","cascade","win-win","historic","inherited","scale","the bubble","wow factor","market leader","touch base","prioritized","alignment","dynamic","brand(ing)"};
	final ArrayList<String> arr = new ArrayList<String>();
	public ArrayAdapter<String> arradapter;
	public static Context context;
	 
	 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edittext);
       
        
        Button editback = (Button) findViewById(R.id.editback); 
        Button save = (Button) findViewById(R.id.save); 
        
      	Typeface font = Typeface.createFromAsset(getAssets(), "good.ttf");  
      	editback.setTypeface(font); 
      	save.setTypeface(font);
        
        
        
        txt1 = (TextView)  findViewById(R.id.txt1);
        et = (EditText)  findViewById(R.id.edittext); 
        context = getApplicationContext();
         
        File file = context.getFileStreamPath(FILENAME);
        if(!file.exists()){	    	 
	    	  	FileOutputStream fos = null; 
	    	  	String string = "";
	    	  	try {
					fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
					fos.write(string.getBytes());
					fos.close();
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}			
		     
        }
		
		try {
		    // open the file for reading
			
		    FileInputStream instream = openFileInput(FILENAME);
		 
		    // if file the available for reading
		    
		      // prepare the file for reading
		      InputStreamReader inputreader = new InputStreamReader(instream);
		      BufferedReader buffreader = new BufferedReader(inputreader);
		 
		      String line;
		 

		      Integer i = 0;		      
		      while (( line = buffreader.readLine()) != null ) {
		    	  if (!line.equalsIgnoreCase("")){
		    		  arr.add(line);
		    	  }
		    	  
		    	  i=i+1;
		      }
		      if (i==0){
		    	  for (int j=0;j<lv_arr.length;j++){
		    		 arr.add(lv_arr[j]); 
		    	  }
		      }
		      
		 
		      	lv1=(ListView)findViewById(R.id.ListView01);
		      	
		      	arradapter= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , arr);
		        
		        lv1.setAdapter(arradapter);
		       // lv1.setOnItemLongClickListener(listener)
		        lv1.setOnItemLongClickListener(new OnItemLongClickListener() {		        
		            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
		            		showToast("Item removed ");
		            		String setEt = arradapter.getItem(arg2).toString();
		            		
		            		arradapter.remove(arradapter.getItem(arg2));
		            	 
		            	 onDelete();
		            	 setEtText(setEt);
		            //arr.remove(arg0.getId());
						return true;
		            
		            	
						
					}

			
		        }); 

		        
		        // close the file again
		    instream.close();
		  } catch (java.io.FileNotFoundException e) {
		    // do something if the myfilename.txt does not exits
		  } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
	
        
        
    }
    
    public void onSave(View v){
    	if(!et.getText().toString().equals("")){
	    	if(saveFile()) showToast("Word added");
    	}
    }
    private void setEtText(String str){
    	et.setText(str);
    }
    private boolean checkDuplicate(String str, ArrayAdapter arr){
    	for (int i=0;i<arr.getCount();i++){
        	if(arr.getItem(i).toString().equalsIgnoreCase(str)) {
        		showToast("Entry already exist");
        		return false;        	 
        	}
        }
    //
    	return true;
    }
   private boolean saveFile(){
	    if(!checkDuplicate(et.getText().toString(),arradapter)) return false;
    	if(et.getText().toString().equals("")) return false;      
    	String string,string2;
    	arradapter.add(et.getText().toString());
        string2= (String) et.getText().toString();
        txt1.setText("");
        for (int i=0;i<arradapter.getCount();i++){
        	String rr = arradapter.getItem(i).toString().replace("\n", " ");
        	txt1.append(rr+"\n");
 
        }

        string= (String) txt1.getText().toString();
        
        FileOutputStream fos = null;

		try {
			fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
			fos.write(string.getBytes());
			fos.close();
			
			//fis = openFileInput(FILENAME);
			//String st = fis.read();
			//et.setText(st);
			//fis.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		et.setText("");
		return true;
    }
   
   private void onDelete(){
	       	     
    	String string;
    	txt1.setText("");
        for (int i=0;i<arradapter.getCount();i++){
        	String rr = arradapter.getItem(i).toString().replace("\n", " ");
        	txt1.append(rr+"\n");
 
        }

        string= (String) txt1.getText().toString();
        
        FileOutputStream fos = null;

		try {
			fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
			fos.write(string.getBytes());
			fos.close();
			
			//fis = openFileInput(FILENAME);
			//String st = fis.read();
			//et.setText(st);
			//fis.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		et.setText("");
	
		
   }
   
   public static boolean fileExists(Context context, String f) {

       String[] filenames = context.fileList();
       for (String name : filenames) {
         if (name.equals(f)) {
           return true;
         }
       }

       return false;
}
   public static void showToast(String str){
	   
	   CharSequence text = str;
	   int duration = Toast.LENGTH_SHORT;

	   Toast toast = Toast.makeText(context, text, duration);
	   toast.show();
   }
   public void onBack(View v){
   	//
   	this.finish();
   	Intent intent = new Intent(getApplicationContext(), MenuActivity.class);    	
   	startActivity(intent);
   }
   public void onBackPressed() {
 	  
 	  this.finish();
       Intent intent = new Intent(getApplicationContext(), MenuActivity.class); 
       //intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
   	  startActivity(intent);
   	
 	  overridePendingTransition(R.anim.moveout, R.anim.moveout);
 	}  
   
   
   

}